package cn.seapon.talker.adapters;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import cn.seapon.talker.R;
import cn.seapon.talker.common.FriendListInfomation;
import cn.seapon.talker.common.FriendListInfomation.FriendInfomation;
import cn.seapon.talker.common.GroupInfo;
import cn.seapon.talker.infocarrier.SharedItems;

/**
 * @author 作者 E-mail:
 * @version 创建时间：2015年1月2日 下午2:33:47 类说明
 */
public class FriendListAdapter extends BaseExpandableListAdapter {
	private static final String TAG = "____FriendListAdapter___";
	private HashMap<String, View> groupViews = new HashMap<String, View>();

	private Context context = null;
	private ArrayList<FriendInfomation> friendEntities;
	private GroupInfo groupInfo;
	// 分组名字
	private String[] category;
	// 与列表项绑定的数据
	private FriendInfomation[][] subcategory;

	public FriendListAdapter(Context context) {
		super();
		this.context = context;
		buildData();

		getCategoryName();
		Log.e(TAG, friendEntities.toString());
		formatEntitiesToArray();
		// for (int i = 0; i < subcategory.length; i++) {
		// Log.d(TAG, "//******************//");
		// for (int j = 0; j < subcategory[i].length; j++) {
		// Log.d(TAG, "__"+subcategory[i][j]);
		// }
		// Log.d(TAG, "//******************//");
		// }
	}

	// @Override
	// public void onGroupCollapsed(int groupPosition) {
	// LinearLayout view = (LinearLayout) groupViews.get(groupPosition+"");
	// for (int i = 0; i < view.getChildCount(); i++) {
	// View child = view.getChildAt(i);
	// if (child instanceof ImageView) {
	// ImageView childImageView = (ImageView)child;
	// childImageView.setImageResource(R.drawable.arrow_right);
	// break;
	// }
	// }
	// super.onGroupCollapsed(groupPosition);
	// }
	//
	// @Override
	// public void onGroupExpanded(int groupPosition) {
	// LinearLayout view = (LinearLayout) groupViews.get(groupPosition+"");
	// for (int i = 0; i < view.getChildCount(); i++) {
	// View child = view.getChildAt(i);
	// if (child instanceof ImageView) {
	// ImageView childImageView = (ImageView)child;
	// childImageView.setImageResource(R.drawable.arrow_down);
	// break;
	// }
	// }
	// super.onGroupExpanded(groupPosition);
	// }

	/**
	 * 初始化朋友列表数据 friendEntities
	 * 
	 */
	private void buildData() {
		friendEntities = new ArrayList<FriendInfomation>();
		FriendListInfomation infos = SharedItems.friendListInfomation;
		for (int i = 0; i < infos.getCount(); i++) {
			FriendInfomation info = infos.getAt(i);
			friendEntities.add(info);
		}
		groupInfo = SharedItems.groupInfo;
	}

	/**
	 * 获得按groupIndex排序后的数组后，得到相应顺序的字符串数组
	 */
	public void getCategoryName() {
		int[] groupIds = groupInfo.getGroupIdByOrder();
		category = new String[groupIds.length];
		for (int i = 0; i < groupIds.length; i++) {
			category[i] = groupInfo.getGroupName(groupIds[i]);
			// Log.e(TAG, category[i]);
		}
	}

	private void formatEntitiesToArray() {
		final int[] groupIds = groupInfo.getGroupIdByOrder();
		subcategory = new FriendInfomation[groupIds.length][];
		for (int i = 0; i < groupIds.length; i++) {
			// final int groupSize = groupInfo.getGroupSize(groupIds[i]);
			int groupSize = 0;
			for (int j = 0; j < friendEntities.size(); j++) {
				if (groupIds[i] == friendEntities.get(j).getGroupid()) {
					groupSize++;
				}
			}
			Log.e(TAG, "groupID为：" + groupIds[i] + " 的groupSize是：" + groupSize);
			FriendInfomation[] row = new FriendInfomation[groupSize];
			int count = 0;
			for (int j = 0; j < friendEntities.size(); j++) {
				if (groupIds[i] == friendEntities.get(j).getGroupid()) {
					row[count++] = friendEntities.get(j);
				}
			}
			subcategory[i] = row;
		}
	}

	// 获得与child绑定的数据
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return null;
	}

	// 定义一个显示文字信息的方法
	private TextView getTextView() {
		AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, 64);
		TextView textView = new TextView(context);
		// 设置 textView控件的布局
		textView.setLayoutParams(layoutParams);
		// 设置该textView中的内容相对于textView的位置,垂直居中
		textView.setGravity(Gravity.CENTER_VERTICAL);
		// 设置txtView的内边距
		textView.setPadding(36, 0, 0, 0);
		// 设置文字大小
		textView.setTextSize(15.0f);
		// 设置文本颜色
		textView.setTextColor(Color.parseColor("#BB000000"));
		return textView;
	}

	// 取得用于显示给定分组的视图. 这个方法仅返回分组的视图对象
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.friend_group_item, parent,
					false);
		}
		// ImageView arrow = (ImageView)
		// convertView.findViewById(R.id.arrow_direction);
		TextView groupName = (TextView) convertView
				.findViewById(R.id.group_name);
		TextView groupNum = (TextView) convertView.findViewById(R.id.group_num);

		String groupNameString = category[groupPosition];
		int groupId = groupInfo.getGroupId(groupNameString);
		groupName.setText(groupNameString);
		groupNum.setText("[" + subcategory[groupPosition].length + "]");
		// arrow.setImageResource(R.drawable.arrow_right);
		return convertView;
	}

	// 取得指定分组的子元素数.
	@Override
	public int getChildrenCount(int groupPosition) {
		int groupid = groupInfo.getGroupId(category[groupPosition]);
		int count = 0;
		for (int i = 0; i < friendEntities.size(); i++) {
			if (friendEntities.get(i).getGroupid() == groupid) {
				count++;
			}
		}
		return count;
	}

	// 取得显示给定分组给定子位置的数据用的视图
	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.friend_list_item, parent,
					false);
		}
		ImageView imageView = (ImageView) convertView.findViewById(R.id.logo);
		TextView textViewNickName = (TextView) convertView
				.findViewById(R.id.nickname);
		TextView textViewSignature = (TextView) convertView
				.findViewById(R.id.signature);

		FriendInfomation info = subcategory[groupPosition][childPosition];
		String nickname = info.getNickname();
		String remarkname = info.getRemarkname();
		String friendId = info.getId();
		// String signature = info.gt
		if ("".equals(remarkname)) {
			textViewNickName.setText(nickname + "（" + friendId + "）");
		} else {
			textViewNickName.setText(remarkname + "（" + friendId + "）");
		}
		String imageName = SharedItems.friendListInfomation.getInfoById(friendId).getAvatar();
		Log.d(TAG, "imageName:"+imageName);
		if ("".equals(imageName) || "null".equals(imageName)) {
			imageView.setBackgroundResource(R.drawable.header);
		} else {
			try {
				imageView.setBackgroundResource(SharedItems.avatarMap
						.get(imageName));
			} catch (Exception e) {
				imageView.setBackgroundResource(R.drawable.header);
			}
		}
		
		if ("null".equals(SharedItems.friendListInfomation.getInfoById(friendId)
				.getSignature())) {
			textViewSignature.setText("");
		}else {
			textViewSignature.setText(SharedItems.friendListInfomation
					.getInfoById(friendId).getSignature());
		}
		convertView.setTag(info);
		return convertView;
	}

	// 取得指定分组的ID，必须唯一
	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	// 取得分组数
	@Override
	public int getGroupCount() {
		return category.length;
	}

	// 取得给定分组中给定子视图的ID. 该组ID必须在组中是唯一的
	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	// 取得与给定分组关联的数据 即分组的名称
	@Override
	public Object getGroup(int groupPosition) {
		return null;
	}

	/**
	 * 指定位置的子视图是否可选择. 设置为FALSE时不可以获得焦点（鼠标点击无效）
	 */
	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}
}